<?php
namespace Modules\Region\Controllers;

use Core\Mvc\Controller;

class AdminController extends Controller
{

    public function indexAction($theme, $region)
    {
        $regionData = $this->entityManager->get('region', ['theme' => $theme, 'region' => $region]);
        $data = $this->entityManager->contentModel('block');
        self::$variables += array(
            '#templates' => array(
                'box',
            ),
            'wrapper' => false,
            'id' => 'right_handle',
            'title' => '添加' . $regionData->name . '区块--选择区块类型',
            'max' => true,
            'color' => 'success',
            'size' => '6',
            'content' => array(
                'termList' => array(
                    '#templates' => 'blockType',
                    'region' => $region,
                    'data' => $data
                ),
            ),
        );
    }

    public function regionAction($theme)
    {
        $themes = $this->config->get('themes');
        if (array_search(ucfirst($theme), $themes) === false) {
            return $this->temMoved(['for' => 'adminRegion', 'theme' => 'AdminLTE']);
        }

        $content = [];
        $data = $this->entityManager->find('region', ['theme' => $theme]);

        $menu = [];
        foreach ($themes as $t) {
            if ($t == 'Default') {
                continue;
            }
            $menu[$t] = [
                'href' => [
                    'for' => 'adminRegion',
                    'theme' => $t,
                ],
                'name' => $t,
            ];
            if ($t == $theme) {
                $menu[$t]['active'] = true;
            }
        }

        self::$variables['title'] = '区域';
        self::$variables['description'] = '区域管理，添加编辑排序区块等';
        self::$variables += array(
            '#templates' => 'page',
            'breadcrumb' => array(
                'module' => array(
                    'name' => '区域',
                ),
            ),
            'content' => &$content,
        );
        $content['themeFilter'] = [
            '#templates' => 'menuTabs',
            'title' => '筛选主题',
            'data' => $menu
        ];

        $content['regionList'] = array(
            '#templates' => 'box',
            'title' => $theme . '主题区块',
            'max' => false,
            'color' => 'primary',
            'size' => '6',
            'wrapper' => true,
            'content' => array(
                'dataList' => array(
                    '#templates' => array(
                        'regionTable',
                        'regionTable-' . $theme,
                    ),
                    'theadDisplay' => true,
                    'thead' => [],
                    'checkAll' => false,
                    'data' => $data,
                ),
            ),
        );
        $content['termHandle'] = array(
            '#templates' => array(
                'box',
                'box-right',
            ),
            'id' => 'right_handle',
            'title' => '操作区',
            'wrapper' => true,
            'max' => true,
            'color' => 'success',
            'size' => '6',
            'content' => array(
                'regionAdd' => '请选择区块编辑',
            ),
        );
    }

    public function sortAction($theme, $region)
    {
        $regionNode = $this->entityManager->get('region', ['theme' => $theme, 'region' => $region]);
        if (!$regionNode) {
            throw new \Exception('参数错误，region不存在');
        }
        $content = [];
        $data = $this->entityManager->find('block', ['theme' => $theme, 'region' => $region]);
        if ($this->request->isPost() && $this->request->hasPost('rh')) {
            $rh = json_decode($this->request->getPost('rh'));
            $blockHierarchy = nestableJsonToArray($rh);
            $state = $this->config->set('m.region.region' . ucfirst($theme) . ucfirst($region) . 'BlockList', $blockHierarchy);
            if ($state) {
                $this->flash->success('区域区块排序成功');
            } else {
                $this->flash->error('区域区块排序失败');
            }
        }
        self::$variables += array(
            '#templates' => 'pageNoWrapper',
            'region' => $region,
            'content' => &$content,
        );
        $content['regionList'] = array(
            '#templates' => 'box',
            'wrapper' => false,
            'id' => 'right_handle',
            'title' => $regionNode->name . ' 区块排序',
            'max' => true,
            'color' => 'success',
            'size' => '6',
            'content' => array(
                'regionBlockSort' => array(
                    '#templates' => array('hierarchical', 'hierarchical-regionBlockSort'),
                    'id' => 'regionBlockSort',
                    'title_display' => false,
                    'data' => $data
                ),
            ),
        );
    }

    public function addAction($theme, $region, $contentModel)
    {
        $content = [];
        $regionNode = $this->entityManager->find('region', ['theme' => $theme, 'region' => $region]);
        if (!$regionNode) {
            throw new \Exception('region不存在：' . $region);
        }
        $blockContentModel = $this->entityManager->contentModel('block');
        if (!isset($blockContentModel[$contentModel])) {
            throw new \Exception('block内容类型' . $contentModel . '不存在');
        }

        $entity = $this->entityManager->get('block');
        $editForm = $entity->setContentModel($contentModel)->setRegion($region)->setTheme($theme)->addForm();
        if ($entity->getSaveState() === true) {
            $this->flashSession->success('保存区块成功');
            return $this->temMoved(array('for' => 'adminRegionBlockSort', 'theme' => $theme, 'region' => $region));
        } elseif ($entity->getSaveState() === false) {
            $this->flashSession->error('保存区块失败');
        }
        self::$variables += array(
            '#templates' => 'pageNoWrapper',
            'content' => &$content,
        );
        $content['regionList'] = array(
            '#templates' => array(
                'box',
            ),
            'wrapper' => false,
            'id' => 'right_handle',
            'title' => "{$region}区域添加 {$blockContentModel[$contentModel]['name']} 区块",
            'max' => true,
            'color' => 'success',
            'size' => '6',
            'content' => array(
                'termList' => $editForm->renderForm(),
            ),
        );
    }

    public function editAction($theme, $region, $block)
    {
        $content = [];
        $regionNode = $this->entityManager->find('region', ['theme' => $theme, 'region' => $region]);
        if (!$regionNode) {
            throw new \Exception('region不存在：' . $region);
        }
        $entity = $this->entityManager->get('block', ['theme' => $theme, 'region' => $region, 'block' => $block]);
        if (!$entity) {
            throw new \Exception('参数错误，block不存在：' . $block);
        }

        $editForm = $entity->editForm();

        if ($entity->getSaveState() === true) {
            $this->flashSession->success('保存区块成功');
            return $this->temMoved(array('for' => 'adminRegionBlockSort', 'theme' => $theme, 'region' => $region));
        } elseif ($entity->getSaveState() === false) {
            $this->flashSession->error('保存区块失败');
        }

        self::$variables += array(
            '#templates' => 'pageNoWrapper',
            'content' => &$content,
        );
        $content['regionList'] = array(
            '#templates' => array(
                'box',
            ),
            'wrapper' => false,
            'id' => 'right_handle',
            'title' => '添加',
            'max' => true,
            'color' => 'success',
            'size' => '6',
            'content' => array(
                'termList' => $editForm->renderForm(),
            ),
        );
    }

    public function blockDeleteAction($theme, $region, $block)
    {
        $regionBlock = $this->entityManager->get('block', ['theme' => $theme, 'region' => $region, 'block' => $block]);
        if (!$regionBlock) {
            $this->flashSession->success('区块不存在，无法被删除');
            return $this->moved(array('for' => 'adminRegionBlockSort','theme'=>$theme, 'region' => $region));
        }
        if ($regionBlock->delete()) {
            $this->flashSession->success('删除成功。');
        } else {
            $this->flashSession->error('删除失败。');
        }

        return $this->moved(array(
            'for' => 'adminRegionBlockSort',
            'theme' => $theme,
            'region' => $region,
        ));
    }
}
